<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-row>
        <el-col :span="4">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="medium"
            @click="handleAdd"
          >新增{{this.title}}</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="itemList"
        border
        v-loading="listLoading"
        fit
        highlight-current-row
        style="width: 90%;"
        stripe
        size="mini"
      >
        <el-table-column
          v-for="column in tableColumns"
          align="center"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              round
              icon="el-icon-edit"
              @click="handleEdit(scope)"
            >编辑</el-button>
            <el-button
              type="danger"
              size="mini"
              round
              icon="el-icon-delete"
              @click="handleDelete(scope)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="30%">
      <el-form
        :model="itemForm"
        :rules="itemFormRules"
        ref="itemFormRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding:0 30px;"
      >
        <el-form-item label="收支项目" prop="name">
          <el-input v-model="itemForm.name" placeholder="输入收支项目" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="handleSave(false)">保存</el-button>
        <el-button type="primary" v-if="dialogType=='new'" @click="handleSave(true)">保存并增加下一个</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getIncomeExpeseItems,
  addIncomeExpeseItem,
  updateIncomeExpeseItem,
  delIncomeExpeseItem,
} from "@/api/calculator";

const defaultForm = {
  id: undefined,
  name: "",
};

export default {
  name: "resItem",
  data() {
    return {
      itemForm: Object.assign({}, defaultForm),
      itemFormRules: {
        name: [{ required: true, message: "请输入收支项", trigger: "blur" }],
      },
      title: "收支项",
      dialogVisible: false,
      dialogType: "new",
      itemList: [],
      listLoading: true,
      tableColumns: [
        {
          key: "id",
          title: "ID",
        },
        {
          key: "name",
          title: "项目名称",
        },
      ],
    };
  },
  computed: {
    getTitle() {
      return this.dialogType == "new"
        ? `新建${this.title}`
        : `编辑${this.title}`;
    },
  },
  created() {
    this.getItems();
  },
  methods: {
    getItems() {
      this.listLoading = true;
      getIncomeExpeseItems()
        .then((res) => {
          this.itemList = res;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },
    // 增加
    handleAdd() {
      this.itemForm = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.itemFormRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.itemForm = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.itemFormRef.clearValidate();
      });
    },
    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delIncomeExpeseItem(row.id);

          this.itemList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async handleSave(flag) {
      this.$refs.itemFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          res = await updateIncomeExpeseItem(this.itemForm);
          const index = this.itemList.findIndex((v) => v.id === res.id);
          this.itemList.splice(index, 1, res);
        } else {
          res = await addIncomeExpeseItem(this.itemForm);
          const { id } = res;
          if (id > 0) {
            this.getItems();
          }
        }

        const { name } = res;
        if (flag) {
          this.itemForm = Object.assign({}, defaultForm);
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>支出项: ${name}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .el-select {
    width: 100%;
  }
}
</style>